package com.health.work.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.health.work.R;
import com.health.work.activity.ExpertListActivity.ViewHolder;
import android.widget.AdapterView.OnItemClickListener;
import com.health.work.model.AddressBean;
import com.health.work.model.QuestionBean;
import com.health.work.model.SellerBean;
import com.health.work.parse.AddressParse;
import com.health.work.parse.TypeParse;
import com.health.work.utils.AssistUtils;
import com.health.work.utils.AsyncImageLoader;
import com.health.work.utils.DefaultJSONData;
import com.health.work.utils.HEALTHPASSPORT;
import com.health.work.utils.RequestParamtersUtil;
import com.health.work.utils.TipsUtil;
import com.health.work.utils.UserInfoUtils;

/**
 * 医疗商圈页面
 * 
 * @author star
 * 
 */
public class MedicalDistrictActivity extends Activity {

	protected View locationTextView;
	protected String location;
	private Button back;
	// private TextView map;

	private ProgressDialog dialog;
	private Spinner spinner1;
	private Spinner spinner2;
	private Spinner spinner3;
	private Spinner spinner4;
	private List<String> spinnerList1;
	private List<String> spinnerList2;
	private List<String> spinnerList3;
	private List<String> spinnerList4;
	private ArrayList<AddressBean> provinceList;
	private ArrayList<AddressBean> cityList;
	private ArrayList<AddressBean> areaList;
	private ArrayList<AddressBean> roadList;
	private String province;
	private String city;
	private String area;
	private String road = "";
	private AddressParse parse;

	private Spinner spinner_product;
	private TypeParse typeParse;
	private String idBusinessType;

	private Thread thread;
	private final static int SUCCESS = 0;
	private final static int FAILE = 1;
	private final static int ERROR = 2;
	private static final int NODATA = 3;
	private static final int SHOWQUESTION = 4;
	public static ArrayList<SellerBean> SellerList;

	private ListView sellerListView;
	private String mobilePhoneNum;

	private double mLatitude = 39.95;// 纬度
	private double mLongitude = 116.37;// 经度

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:
				TipsUtil.showAlert(MedicalDistrictActivity.this, null,
						"数据请求成功！");
				break;
			case FAILE:
				TipsUtil.showAlert(MedicalDistrictActivity.this, null,
						"数据请求失败！");
				break;
			case ERROR:
				TipsUtil.showAlert(MedicalDistrictActivity.this, null, "未知错误！");
				break;
			case NODATA:
				TipsUtil.showAlert(MedicalDistrictActivity.this, null,
						"暂无商家数据！");
				break;
			case SHOWQUESTION:
				SellerAdapter adapter = new SellerAdapter(
						MedicalDistrictActivity.this);
				sellerListView.setAdapter(adapter);
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.medical_district_layout);
		mobilePhoneNum = UserInfoUtils.getUserProperty(this,
				HEALTHPASSPORT.MOBILEPHONE);
		initPages();
	}

	private void initPages() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			mobilePhoneNum = (String) bundle.getString("mobilePhoneNum");
		}

		back = (Button) findViewById(R.id.btnBack);
		// map = (TextView) findViewById(R.id.map);
		sellerListView = (ListView) findViewById(R.id.doctorlist);
		// map.setOnClickListener(onClickListener);
		back.setOnClickListener(onClickListener);
		request("0", 1);
		// getData();
		sellerListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent;
				intent = new Intent(MedicalDistrictActivity.this,
						Products.class);
				intent.putExtra("BusinessTypeId",
						SellerList.get(arg2).BusinessTypeId);
				startActivity(intent);
			}
		});
	}

	OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btnBack:
				finish();
				break;
			// case R.id.map:
			// // getLocation();
			//
			// //此处进入地图，切记要传经纬度坐标 mLatitude是纬度；mLongitude是经度
			// gotoMap(mLatitude,mLongitude);
			//
			// break;
			default:
				break;
			}
		}

	};

	/*
	 * zhailong 由此进入地图，必须包含经纬度，否则是用默认位置！latitude是纬度；longitude是经度
	 */
	private void gotoMap(double latitude, double longitude) {
		Intent intent = new Intent();
		intent.setClass(MedicalDistrictActivity.this, MyLocActivity.class);
		intent.putExtra("Latitude", latitude);// 传入纬度值
		intent.putExtra("Longitude", longitude);// 传入经度值
		startActivity(intent);
	}

	protected Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 2:
				intent2Map();
				break;
			}
		}
	};

	/**
	 * 获取商家信息
	 */
	private void getData() {

		thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new RequestParamtersUtil().SelectBusiness(province, city, area,
						road, idBusinessType, "", "", new DefaultJSONData() {

							@Override
							public void parse(String result)
									throws JSONException {
								// TODO Auto-generated method stub
								Log.e("0", result.toString());
								if ("0".equals(result)) {
									handler.sendEmptyMessage(NODATA);
								}
							}

							@Override
							public void parse(JSONObject object)
									throws JSONException {
								// TODO Auto-generated method stub
							}

							@Override
							public void parse(JSONArray array)
									throws JSONException {
								// TODO Auto-generated method stub
								Log.e("2", array.toString());
								if (array.toString() != null
										&& array.length() > 0) {
									SellerList = new ArrayList<SellerBean>();
									for (int i = 0; i < array.length(); i++) {
										SellerBean bean = new SellerBean();
										bean.BusinessAddress = array
												.getJSONObject(i).optString(
														"BusinessAddress");
										bean.BusinessType = array
												.getJSONObject(i).optString(
														"BusinessType");
										bean.BusinessTypeId = array
												.getJSONObject(i).optInt(
														"BusinessTypeId");
										bean.City = array.getJSONObject(i)
												.optInt("City");
										bean.CountyArea = array
												.getJSONObject(i).optInt(
														"CountyArea");
										bean.CreateDate = array
												.getJSONObject(i).optString(
														"CreateDate");
										bean.Discount = array.getJSONObject(i)
												.optInt("Discount");
										bean.Id = array.getJSONObject(i)
												.optInt("Id");
										bean.IDNumber = array.getJSONObject(i)
												.optString("IDNumber");
										bean.Integral = array.getJSONObject(i)
												.optInt("Integral");
										bean.Introduce = array.getJSONObject(i)
												.optString("Introduce");
										bean.IsThrough = array.getJSONObject(i)
												.optString("IsThrough");
										bean.MainCommodities = array
												.getJSONObject(i).optString(
														"MainCommodities");
										bean.MembershipType = array
												.getJSONObject(i).optString(
														"MembershipType");
										bean.MobilePhone = array.getJSONObject(
												i).optString("MobilePhone");
										bean.Name = array.getJSONObject(i)
												.optString("Name");
										bean.PassWord = array.getJSONObject(i)
												.optString("PassWord");
										bean.PersonalPhotos = array
												.getJSONObject(i).optString(
														"PersonalPhotos");
										bean.Photo = array.getJSONObject(i)
												.optString("Photo");
										bean.Promise = array.getJSONObject(i)
												.optString("Promise");
										bean.Province = array.getJSONObject(i)
												.optInt("Province");
										bean.Quipmentid = array
												.getJSONObject(i).optString(
														"Quipmentid");
										bean.ServiceAttendance = array
												.getJSONObject(i).optInt(
														"ServiceAttendance");
										bean.Sex = array.getJSONObject(i)
												.optString("Sex");
										bean.Lat = array.getJSONObject(i)
												.optDouble("Lat");
										bean.Lng = array.getJSONObject(i)
												.optDouble("Lng");
										bean.Township = array.getJSONObject(i)
												.optInt("Township");
										SellerList.add(bean);
									}
									handler.sendEmptyMessage(SHOWQUESTION);
								}
							}
						});
			}
		});
		thread.start();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	public void intent2Map() {
		if (location.equals("")) {
			Toast.makeText(MedicalDistrictActivity.this, "无法获取您的位置",
					Toast.LENGTH_SHORT).show();
		} else {
			Intent intent = new Intent();
			intent.setClass(MedicalDistrictActivity.this, MyLocActivity.class);
			startActivity(intent);
		}
	}

	private void spinnerother() {// 其它的类别
		if (typeParse == null) {
			return;
		}
		spinner_product = (Spinner) this
				.findViewById(R.id.spinner_product_kink);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item,
				typeParse.nameListBusinessType);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_product.setAdapter(adapter);
		spinner_product
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int pos, long arg3) {
						idBusinessType = typeParse.typeListBusinessType
								.get(pos).TypeId;
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						idBusinessType = typeParse.typeListBusinessType.get(0).TypeId;
					}
				});
	}

	private void spinnerRelation1() {// 省
		if (spinnerList1 == null) {
			return;
		}
		spinner1 = (Spinner) this.findViewById(R.id.spinner1);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList1);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner1.setAdapter(adapter);
		spinner1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				request(provinceList.get(pos).provinceId, 2);
				province = provinceList.get(pos).provinceId;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				province = provinceList.get(0).provinceId;
			}
		});
	}

	private void spinnerRelation2() {// 市
		if (spinnerList2 == null) {
			return;
		}
		spinner2 = (Spinner) this.findViewById(R.id.spinner2);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList2);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner2.setAdapter(adapter);
		spinner2.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				request(cityList.get(pos).provinceId, 3);
				city = cityList.get(pos).provinceId;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				city = cityList.get(0).provinceId;
			}
		});
	}

	private void spinnerRelation3() {// 区
		if (spinnerList3 == null) {
			return;
		}
		spinner3 = (Spinner) this.findViewById(R.id.spinner3);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList3);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner3.setAdapter(adapter);
		spinner3.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				request(areaList.get(pos).provinceId, 4);
				area = areaList.get(pos).provinceId;
//				getData();
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				area = areaList.get(0).provinceId;
			}
		});
	}

	private void spinnerRelation4() {// 其它
		if (spinnerList4 != null) {
			spinner4 = (Spinner) this.findViewById(R.id.spinner4);
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_item, spinnerList4);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner4.setAdapter(adapter);
			spinner4.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int pos, long arg3) {
					road = roadList.get(pos).provinceId;
					getData();
				}

				public void onNothingSelected(AdapterView<?> arg0) {
					road = roadList.get(0).provinceId;
				}
			});
		}else{
			getData();
		}
	}

	protected void request(final String provinceId, final int i) {
		final Context context = this;
		AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPreExecute() {
				if (dialog != null) {

				} else {
					dialog = ProgressDialog.show(context, "", "正在加载数据，请稍候...");
					dialog.setCancelable(true);
				}

				if (typeParse == null) {
					typeParse = new TypeParse();
				}
				parse = new AddressParse();
			}

			@Override
			protected Void doInBackground(Void... params) {
				new RequestParamtersUtil().GetByUpId(provinceId, parse);
				if (typeParse.typeListBusinessType != null) {

				} else {
					new RequestParamtersUtil().GetBusiness(typeParse);
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				if (spinner_product == null) {
					spinnerother();
				}

				if (i == 1) {
					provinceList = parse.addressList;
					spinnerList1 = parse.nameList;
					spinnerRelation1();
				} else if (i == 2) {
					cityList = parse.addressList;
					spinnerList2 = parse.nameList;
					spinnerRelation2();
				} else if (i == 3) {
					areaList = parse.addressList;
					spinnerList3 = parse.nameList;
					spinnerRelation3();
				} else if (i == 4) {
					roadList = parse.addressList;
					spinnerList4 = parse.nameList;
					spinnerRelation4();
					dialog.dismiss();
					dialog = null;
				}
			}
		};
		asyncLoad.execute(null);
	}

	private class SellerAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private AsyncImageLoader asyncImageLoader;
		Activity context;

		public SellerAdapter(Context context) {
			this.context = (Activity) context;
			asyncImageLoader = new AsyncImageLoader();
			inflater = this.context.getLayoutInflater();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return SellerList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return SellerList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder viewHodler;
			if (convertView == null) {
				viewHodler = new ViewHolder();
				convertView = inflater.inflate(R.layout.seller_item, parent,
						false);
				viewHodler.headImageView = (ImageView) convertView
						.findViewById(R.id.touxiang);
				viewHodler.jifenTextView = (TextView) convertView
						.findViewById(R.id.jifen);
				viewHodler.mainTextView = (TextView) convertView
						.findViewById(R.id.main_saile);
				viewHodler.nameTextView = (TextView) convertView
						.findViewById(R.id.name);
				viewHodler.promiseTextView = (TextView) convertView
						.findViewById(R.id.promise);
				viewHodler.serverTextView = (TextView) convertView
						.findViewById(R.id.server);
				viewHodler.map = (TextView) convertView.findViewById(R.id.map);
			} else {
				viewHodler = (ViewHolder) convertView.getTag();
			}
			final SellerBean bean = SellerList.get(position);
			viewHodler.nameTextView.setText(bean.Name);
			viewHodler.mainTextView.setText("主营：" + bean.MainCommodities);
			viewHodler.promiseTextView.setText("商家承诺：" + bean.Promise);
			viewHodler.serverTextView.setText("服务次数：" + bean.ServiceAttendance
					+ "");
			viewHodler.jifenTextView.setText("积分：" + bean.Integral + "");
			if (bean.PersonalPhotos != null) {
				Drawable drawable = asyncImageLoader
						.loadImageFromUrl(bean.PersonalPhotos);
				if (drawable != null) {
					viewHodler.headImageView.setImageDrawable(drawable);
				} else {
					viewHodler.headImageView
							.setImageResource(R.drawable.head_scu);
				}
			}
			viewHodler.map.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Log.e("gotoMap", bean.Lat + "      " + bean.Lng);
					gotoMap(bean.Lat, bean.Lng);
				}
			});
			convertView.setTag(viewHodler);
			return convertView;
		}
	}

	class ViewHolder {
		public ImageView headImageView;
		public TextView nameTextView;
		public TextView mainTextView;
		public TextView promiseTextView;
		public TextView serverTextView;
		public TextView jifenTextView;
		public TextView map;
	}
}
